import userProfileRepository from '../database/repositories/userProfileRepository'
import { ok, fail } from '../utils/response'

export class UserProfileService {
    static saveProfile(storeUserId: string, profileData: any) {
        const jsonStr = JSON.stringify(profileData)
        userProfileRepository.insert(storeUserId, jsonStr)
        return ok({ storeUserId })
    }

    static getProfile(storeUserId: string) {
        const jsonStr = userProfileRepository.getByStoreUserId(storeUserId)
        if (!jsonStr) {
            return fail('用户档案不存在', 404)
        }
        try {
            const profileData = JSON.parse(jsonStr)
            return ok(profileData)
        } catch (error) {
            return fail('用户档案数据格式错误', 500)
        }
    }

    static getAllProfiles() {
        const profiles = userProfileRepository.getAll()
        const result = profiles.map(p => {
            try {
                return { store_user_id: p.store_user_id, profile_data: JSON.parse(p.profile_data) }
            } catch {
                return { store_user_id: p.store_user_id, profile_data: null }
            }
        })
        return ok(result)
    }
}

export default UserProfileService
